package com.senac.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.senac.model.Usuario;

@WebFilter(urlPatterns="*")
public class LoginFilter implements Filter {

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	@Override
	public void destroy() {
	}
	
	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) arg0;
		HttpServletResponse resp = (HttpServletResponse) arg1;
		
		Usuario user = (Usuario) req.getSession().getAttribute("sessionUser");
		if(user == null && !notProtected(req)) {
			resp.sendRedirect("login.jsp");
		} else {
			arg2.doFilter(arg0, arg1);
		}
	}
	
	private boolean notProtected(HttpServletRequest req) {
		String url = req.getRequestURI();
		int index = url.indexOf("?");
		url = url.substring(0, (index < 1 ? url.length() : index));
		
		return url.contains("login.jsp") || url.contains("loginServlet") || url.contains("img/") || url.contains("css/"); 
	}
}
